package com.example.excelimporter.service;

import com.example.excelimporter.model.ImportStatistics;
import com.example.excelimporter.repository.ImportStatisticsRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ImportStatisticsServiceImpl implements ImportStatisticsService {

    @Autowired
    private ImportStatisticsRepository statisticsRepository;

    @Override
    public List<ImportStatistics> getStatisticsByTemplateId(String templateId) {
        return statisticsRepository.findByTemplateId(templateId);
    }

    @Override
    public List<ImportStatistics> getStatisticsByTargetTable(String targetTable) {
        return statisticsRepository.findByTargetTable(targetTable);
    }

    @Override
    public List<ImportStatistics> getStatisticsByTemplateAndTable(String templateId, String targetTable) {
        return statisticsRepository.findByTemplateIdAndTargetTable(templateId, targetTable);
    }

    @Override
    public Map<String, Object> getAggregatedStatistics(String templateId, String targetTable) {
        List<ImportStatistics> stats = statisticsRepository.findByTemplateIdAndTargetTable(templateId, targetTable);
        
        Map<String, Object> aggregated = new HashMap<>();
        aggregated.put("totalImports", stats.size());
        aggregated.put("totalRecords", stats.stream().mapToInt(ImportStatistics::getTotalRecords).sum());
        
        // Calculate average records per import
        double avgRecords = stats.isEmpty() ? 0 : 
            stats.stream().mapToInt(ImportStatistics::getTotalRecords).average().orElse(0);
        aggregated.put("averageRecordsPerImport", avgRecords);
        
        // Get latest statistics
        stats.stream()
            .max(Comparator.comparing(ImportStatistics::getCalculatedAt))
            .ifPresent(latest -> {
                aggregated.put("latestStatistics", latest.getStatistics());
                aggregated.put("latestProcessingResults", latest.getProcessingResults());
            });
            
        return aggregated;
    }

    @Override
    public Map<String, Object> getTrendAnalysis(String templateId, String targetTable, int days) {
        LocalDateTime endDate = LocalDateTime.now();
        LocalDateTime startDate = endDate.minusDays(days);
        
        List<ImportStatistics> stats = statisticsRepository.findByTemplateIdAndTargetTable(templateId, targetTable)
            .stream()
            .filter(stat -> {
                LocalDateTime statDate = stat.getCalculatedAt().toInstant()
                    .atZone(ZoneId.systemDefault())
                    .toLocalDateTime();
                return !statDate.isBefore(startDate) && !statDate.isAfter(endDate);
            })
            .collect(Collectors.toList());
            
        Map<String, Object> trends = new HashMap<>();
        
        // Calculate daily metrics
        Map<Date, List<ImportStatistics>> dailyStats = stats.stream()
            .collect(Collectors.groupingBy(ImportStatistics::getCalculatedAt));
            
        List<Map<String, Object>> dailyMetrics = dailyStats.entrySet().stream()
            .map(entry -> {
                Map<String, Object> daily = new HashMap<>();
                daily.put("date", entry.getKey());
                daily.put("imports", entry.getValue().size());
                daily.put("totalRecords", entry.getValue().stream()
                    .mapToInt(ImportStatistics::getTotalRecords)
                    .sum());
                return daily;
            })
            .collect(Collectors.toList());
            
        trends.put("dailyMetrics", dailyMetrics);
        
        // Calculate overall trends
        if (!stats.isEmpty()) {
            double avgRecordsPerDay = stats.stream()
                .mapToInt(ImportStatistics::getTotalRecords)
                .average()
                .orElse(0);
                
            trends.put("averageRecordsPerDay", avgRecordsPerDay);
            trends.put("totalDaysAnalyzed", dailyStats.size());
            trends.put("totalImports", stats.size());
        }
        
        return trends;
    }
} 